/*
 * =====================================================================================
 *
 *       Filename:  echo_tcp_cli.cpp
 *
 *    Description:  echo的客户端程序
 *
 *        Version:  1.0
 *        Created:  2008年09月01日 14时54分59秒
 *       Revision:  none
 *       Compiler:  g++
 *
 *         Author:  ZhixiongHong (hzx), fishwarter@gmail.com
 *        Company:  Unioncast
 *
 * =====================================================================================
 */

#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <iostream>

using namespace std;

#define SERV_PORT		9800
#define LISTENQ			16
#define MAX_LINE		2048


void str_cli(FILE* fp, int sockfd);

int main(int argc, char** argv)
{
	int					sockfd;
	struct sockaddr_in	servaddr;
	
	if( argc != 2)
	{
		cout << "Usage: echo_tcp_cli ipaddress" << endl;
		return -1;
	}

	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if( sockfd < 0 )
	{
		cout << "create sockfd error " << endl;
		return -1;
	}

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(SERV_PORT);
	servaddr.sin_addr.s_addr = inet_addr(argv[1]);
	
	int retint = connect(sockfd, (sockaddr *)&servaddr, sizeof(servaddr));
	if( retint )		
	{
		cout << "can't connect to server " << endl;
		return -1;
	}
	str_cli(stdin, sockfd);

	return 0;
}

void str_cli(FILE* fp, int sockfd)
{
	char recvline[MAX_LINE];
	char* sendline = NULL;
	size_t len = MAX_LINE;
	while( getline(&sendline, &len, fp) != -1 )
	{
		cout << "send to svr " << endl;
		write(sockfd, sendline, len);
		sleep(5);
		write(sockfd, sendline, len);
again:
		ssize_t n; 
		while( ( n = read(sockfd, recvline, MAX_LINE)) > 0 )	
		{
			//cout <<"n "  << n << endl;
			cout << recvline << endl;
			if( n < 0 && errno == EINTR)
				goto again;
			else if(n < 0)
				cout << "str_echo: read error " << endl;

		}
	}
	cout  << "nnd " << endl;
}




